<template>
  <div>
    <!-- <vx-card>
      <div class="departmentSearchTop">
        <vs-input
          label="部门名称"
          size="small"
          icon="icon-search"
          icon-pack="feather"
          icon-after="true"
          class="inputx no-icon-border"
          v-model="templateFormData.name"
        />
        <vs-button
          color="primary"
          icon="icon-search"
          icon-pack="feather"
          @click="filterRole(selectNodeId)"
          size="small"
        >查找</vs-button>
      </div>
    </vx-card> -->
    <div class="mt-2">
      <div class="vx-row">
        <div class="vx-col w-full md:w-1/3">
          <vx-card>
            <template v-slot:header>
              <div class="title">
                <h4>部门树</h4>
                <vs-button
                  color="primary"
                  icon="icon-plus"
                  icon-pack="feather"
                  @click="handleAddDepartment"
                  size="small"
                  :disabled="isAdd"
                >新增</vs-button>
              </div>
            </template>
            <VuePerfectScrollbar class="mt-5 scroll-area">
              <tree-component
                :data="treeData"
                @node-click="chooseItem"
                :render-content="renderContent"
                node-key="id"
                :default-expanded-keys="expandedIds"
              ></tree-component>
            </VuePerfectScrollbar>
          </vx-card>
        </div>
        <div class="vx-col w-full md:w-2/3">
          <department-table
            :pageSize="pageSize"
            :parentData="tableData"
            :recordsTotal="recordsTotal"
            @loadData="reloadData"
            @loadDataDel="reloadDataDel"
            @filterUserGroup="filterUserGroup"
          ></department-table>
        </div>
      </div>
    </div>
    <!--新增模态框开始 -->
    <vx-popup
      title="新增"
      :active.sync="popupActivo"
      :isValid="isAddValidate"
      @confirmPopup="confirmAdd"
      @cancelPopup="popupActivo = false"
    >
      <vs-select label="类型：" v-model="addDepartmentData.type" class="mt-2 red" @change="changeType">
        <vs-select-item
          :key="index"
          :value="item.value"
          :text="item.text"
          v-for="(item, index) in addDepartmentType"
        />
      </vs-select>
      <div>
        <div v-if="addDepartmentData.type == 4 && popupActivo">
          <vs-select
            label="桥梁："
            class="mt-2"
            v-model="addDepartmentData.name"
            v-if="this.siteData.length"
          >
          <vs-select-item
              :key="item.id"
              :value="item.name"
              :text="item.name"
              v-for="item in siteData"
            />
          </vs-select>
          <!-- <el-select
            label="桥梁："
            class="mt-2"
            v-model="addDepartmentData.name"
            v-if="this.siteData.length"
          >
          <el-option
              :key="item.id"
              :value="item.name"
              :text="item.name"
              v-for="item in siteData"
            />
          </el-select> -->
          <vs-select label="桥梁：" class="mt-2" v-else>
            <vs-select-item text="暂无数据" />
          </vs-select>
        </div>
        <div  v-else>
          <vs-input
            label="名称："
            class="inputx mt-2 red"
            v-model="addDepartmentData.name"
            name="名称"
            v-validate="'required'"
            data-vv-validate-on="input|blur"
          />
          <span
            class="text-danger text-sm"
            v-show="errorBags.has('名称')"
          >{{ errorBags.first('部名称')}}</span>
        </div>
      </div>
      <vs-input label="备注：" class="inputx mt-2" v-model="addDepartmentData.remark" />
      <div v-show="addDepartmentData.type != 4">
        <vs-input
          label="code："
          class="inputx red"
          v-model="addDepartmentData.code"
          name="code"
          data-vv-validate-on="input|blur"
          v-validate="'required|numeric'"
        />
        <span
          class="text-danger text-sm"
          v-show="errorBags.has('code')"
        >{{ errorBags.first('code')}}</span>
      </div>
    </vx-popup>
    <!-- 新增模态框结束 -->
  </div>
</template>
<script>
import departmentTable from "./departmentTable.vue";
import TreeComponent from "@/components/model-tree/ModelTree.vue";
import VuePerfectScrollbar from "vue-perfect-scrollbar";

export default {
  data() {
    return {
      expandedIds: ["-1"],
      isAdd: true,
      templateFormData: {
        name: ""
      },
      selectNodeId: "",
      addDepartmentData: {
        name: "",
        remark: "",
        type: "1",
        parentId: "",
        code: ""
      },
      popupActivo: false,
      addDepartmentType: [],
      tableData: [],
      recordsTotal: 0,
      currentPage: 1,
      treeData: [
        {
          id: "-1",
          name: "我的组织",
          type: 0,
          children: []
        }
      ],
      siteData: [],
      nodeType: "",
      pageSize: 7
    };
  },
  computed: {
    isAddValidate() {
      if (this.addDepartmentData.type != 4) {
        return (
          !this.errorBags.any() &&
          this.addDepartmentData.name != "" &&
          this.addDepartmentData.code != ""
        );
      } else {
        return this.siteData.length != 0;
      }
    }
  },
  methods: {
    //分页
    filterUserGroup(pageNum) {
      this.currentPage = pageNum;
      this.filterRole(this.selectNodeId, pageNum);
    },
    //树名称显示
    renderContent(h, { node }) {
      let iconSkin;
      if (node.data.type == 5) {
        iconSkin = "icon-department";
      } else if (node.data.type == 3) {
        iconSkin = "icon-center";
      } else if (node.data.type == 4) {
        iconSkin = "icon-site";
      } else {
        iconSkin = "icon-group";
      }
      return (
        <span class="custom-tree-node flex items-center">
          <i class={`othericon ${iconSkin}`} />
          <span style="margin-left:5px;">{node.data.name}</span>
        </span>
      );
    },
    //查询表格数据
    filterRole(nodeId, pageStart) {
      nodeId == "" ? (nodeId = -1) : "";
      this.$api.accessControl
        .departmentFilter(nodeId, {
          start: pageStart || 0,
          length: this.pageSize,
          deptName: this.templateFormData.name
        })
        .then(res => {
          this.tableData = res.data.data;
          // console.log(this.treeData[0].children.length,"length!!!!")
          this.recordsTotal = res.data.recordsTotal;
        })
        .catch(() => {});
    },
    //树数据
    getTreeData() {
      this.$api.accessControl
        .departmentTree()
        .then(res => {
          this.treeData[0].children = res.data.data;
        })
        .catch(() => {});
    },
    //部门树-选择
    chooseItem(node) {
      console.log(node, "/?????");
      this.nodeType = node.type;
      if (node.id == -1) {
        this.addDepartmentType = [
          { text: "根目录", value: 1 },
          { text: "集团", value: 2 }
        ];
      } else {
        if (node.type == 1 || node.type == 2) {
          // this.addDepartmentType = [{ text: "中心", value: 3 }];
          this.addDepartmentType = [
            { text: "中心", value: 3 },
            { text: "桥梁", value: 4 },
            { text: "部门", value: 5 }
          ];
        }
        if (node.type == 3) {
          this.addDepartmentType = [
            { text: "桥梁", value: 4 },
            { text: "部门", value: 5 }
          ];
        }
        if (node.type == 4) {
          this.addDepartmentType = [{ text: "部门", value: 5 }];
        }
      }
      this.selectNodeId = node.id;
      this.filterRole(node.id, this.currentPage);
    },
    //新增部门
    handleAddDepartment() {
      // console.log(this.nodeType);
      if (this.treeData[0].children.length >= 10) {
        this.$vs.notify({
          text: "根目录和集团数量已达上限，无法新增",
          color: "danger"
        });
        return;
      }
      if (this.nodeType == 5) {
        this.$vs.notify({
          text: "部门节点下无法新增",
          color: "danger"
        });
        return;
      }
      this.popupActivo = true;
      Object.keys(this.addDepartmentData).map(
        key => (this.addDepartmentData[key] = "")
      );
      console.log(this.addDepartmentData);
      console.log(Object.keys(this.addDepartmentData));
      if (this.addDepartmentType.length < 2) {
        this.addDepartmentData.type = this.addDepartmentType[0].value;
        this.changeType();
      } else {
        if (this.addDepartmentType.length == 2) {
          this.addDepartmentData.type = this.addDepartmentType[0].value;
        } else {
          this.addDepartmentData.type = this.addDepartmentType[0].value;
          this.siteData && this.siteData.length
            ? (this.addDepartmentData.name = this.siteData[0].name)
            : "";
        }
      }
      // console.log(1111111)
      // this.addDepartmentData.name = ''
      // console.log(222222222)
      
    },
    changeType() {
      if (
        this.addDepartmentData.type == "4" &&
        this.siteData &&
        this.siteData.length
      ) {
        this.addDepartmentData.name = this.siteData[0].name;
      } else {
        this.addDepartmentData.name = "";
      }
      if(this.addDepartmentData.type == "4"){
        this.getSite()
      }else{
        this.siteData = []
      }
    },
    confirmAdd() {
      this.popupActivo = false;
      let params = this.addDepartmentData;
      if (this.addDepartmentData.type == "4") {
        let obj = {};
        obj = this.siteData.find(item => {
          return item.name === this.addDepartmentData.name; //筛选出匹配数据
        });
        this.addDepartmentData.code = obj.id;
      }
      params.parentId = this.selectNodeId ? this.selectNodeId : -1;
      this.$api.accessControl
        .departmentAdd(params)
        .then(res => {
          console.log(res)
          if (res.data.success) {
            this.$vs.notify({ text: "添加成功", color: "success" });
            this.filterRole(params.parentId, this.currentPage);
            this.getTreeData();
            this.expandedIds = [params.parentId];
          } else {
            if(res.data.message)
            this.$vs.notify({ text: res.data.message, color: "danger" });
          }
        })
        .catch();
    },
    reloadData(id, pid) {
      if (!id) {
        this.getTreeData();
        this.filterRole(pid, this.currentPage);
        this.expandedIds = [pid];
      } else {
        this.filterRole(id, this.currentPage);
      }
    },
    reloadDataDel(pid) {
      this.getTreeData();
      this.expandedIds = [pid];
      this.filterRole(this.selectNodeId);
    },
    getSite(){
      this.$api.accessControl.getAppBridgeAll()
      .then(res => {
        console.log(res,'桥梁')
        if (res.data.success) {
          this.siteData = res.data.data[0];
        }
      })
      .catch();
    }
  },
  components: {
    departmentTable,
    TreeComponent,
    VuePerfectScrollbar
  },
  mounted() {
    this.filterRole("-1");
    this.getTreeData();
    // this,getSite()
  },
  watch: {
    selectNodeId() {
      // console.log(this.nodeType);
      // console.log(this.selectNodeId)
      if (this.nodeType != 5) {
        if (this.selectNodeId) {
          if (this.treeData[0].children.length>2 && this.selectNodeId == -1) {
            this.isAdd = true;
          } else {
            this.isAdd = false;
          }
        } else {
          this.isAdd = true;
        }
        // this.isAdd = false;
      } else {
        this.isAdd = true;
      }
      // if(this.nodeType == 5)
      // this.isAdd = true;
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/scss/baseColor.scss";
@import "~@/assets/fonts/other-icon/iconfont.css";
.departmentSearchTop {
  height: 4rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .vs-component.vs-con-input-label.vs-input {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    width: 22rem;
    /deep/ .vs-input--label {
      margin-right: 0.8rem;
    }
    /deep/ .vs-inputx.vs-input--input.hasIcon.icon-after-input {
      padding: 0.7rem 1rem !important;
    }
  }
}

.scroll-area {
  height: calc(var(--vh, 1vh) * 100 - 24.2rem);
}

.title {
  display: flex;
  justify-content: space-between;
}
//弹窗
/deep/ .vs-popup {
  width: 400px;
  .con-select,
  .vs-input {
    width: 100%;
  }
}
/deep/.vs-input--input.normal,
/deep/.vs-select--input {
  font-size: 11.9px;
}
/deep/ i.othericon {
  color: $mainColor;
  font-size: 18px;
}
</style>



